import { getCinemaList } from "@/services/cinema";
import { SpinLoading } from "antd-mobile";
import { useMemo, useState } from "react";
import { useRequest } from "umi";
import CinemasHeader from "./components/header";

const CinemasPage = () => {
  // 当前选择的购票方式
  const [ticketFlag, setTicketFlag] = useState("1");

  const { data, error, loading } = useRequest(() => getCinemaList(ticketFlag), {
    refreshDeps: [ticketFlag],
  });

  // 区县集合
  const districts = useMemo(() => {
    let tmp =
      data?.cinemas.map((item) => ({
        districtId: item.districtId,
        districtName: item.districtName,
      })) || [];

    // 去重
    let result: IDistrict[] = [];
    tmp.forEach((item) => {
      const index = result.findIndex(
        (aaa) => aaa.districtId === item.districtId
      );
      if (index === -1) {
        result.push(item);
      }
    });

    // 处理一个全程
    result.unshift({ districtId: 0, districtName: "全城" });
    return result;
  }, [data]);
  // 当前选择的区县Id
  const [districtId, setDistrictId] = useState(0);

  // 区县按钮选择点击
  const handleDistrictChange = (id: number) => {
    console.log("1111", id);
    setDistrictId(id);
  };
  // 购票方式选择点击
  const handleTicketFlagChange = (value: string) => {
    console.log("222", value);
    setTicketFlag(value);
  };

  // 用于展示的 cinemas
  const cinemas = useMemo(() => {
    if (districtId === 0) {
      // 全城数据
      return data?.cinemas || [];
    }

    return data?.cinemas.filter((item) => item.districtId === districtId) || [];
  }, [data, districtId]);

  if (loading) {
    // 请求中
    return (
      <div>
        <SpinLoading />
      </div>
    );
  }

  if (error) {
    // 请求出错
    return <div>请求出错了</div>;
  }

  return (
    <div className="cinemas-page">
      <CinemasHeader
        districts={districts}
        districtId={districtId}
        ticketFlag={ticketFlag}
        onDistrictChange={handleDistrictChange}
        onTicketFlagChange={handleTicketFlagChange}
      />

      <p>{cinemas.length}</p>
      <ul>
        {cinemas.map((item) => {
          return <li key={item.cinemaId}>{item.name}</li>;
        })}
      </ul>
    </div>
  );
};

export default CinemasPage;
